package com.iflyings.android.util

import com.iflyings.android.util.ByteUtils.toHexString
import java.io.FileInputStream
import java.security.MessageDigest
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.DESKeySpec
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi

object EncryptUtils {
    fun getFileMD5(filePath: String): String {
        val md5 = MessageDigest.getInstance("MD5")
        val buffer = ByteArray(1024)

        FileInputStream(filePath).use { fis ->
            var length: Int
            while ((fis.read(buffer).also { length = it }) != -1) {
                md5.update(buffer, 0, length)
            }
        }

        return toHexString(md5.digest())
    }

    // 将此换成 MD5、SHA-1、SHA-256、SHA-512、SHA-384 等参数
    fun encryptMD5(buffer: ByteArray): String = encryptString(buffer, "MD5")

    fun encryptSha256(buffer: ByteArray): String = encryptString(buffer, "SHA-256")

    fun encryptString(buffer: ByteArray, algorithm: String): String {
        val md5 = MessageDigest.getInstance(algorithm)
        md5.update(buffer)
        return toHexString(md5.digest())
    }

    @OptIn(ExperimentalEncodingApi::class)
    fun encrypt(content: String, secretKey: String, algorithm: String = "DES"): String {
        val keySpec = DESKeySpec(secretKey.toByteArray())
        val key = SecretKeyFactory.getInstance(algorithm).generateSecret(keySpec)
        val cipher = Cipher.getInstance(algorithm)
        cipher.init(Cipher.ENCRYPT_MODE, key)

        return Base64.encode(cipher.doFinal(content.toByteArray()))
    }

    @OptIn(ExperimentalEncodingApi::class)
    fun decrypt(content: String, secretKey: String, algorithm: String = "DES"): String {
        val keySpec = DESKeySpec(secretKey.toByteArray())
        val key = SecretKeyFactory.getInstance(algorithm).generateSecret(keySpec)
        val cipher = Cipher.getInstance(algorithm)
        cipher.init(Cipher.DECRYPT_MODE, key)

        val encryptedWithoutB64 = Base64.decode(content)
        val plainTextPwdBytes = cipher.doFinal(encryptedWithoutB64)
        return String(plainTextPwdBytes)
    }

}